package spacecrack;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;

public class GameManager {
	@SuppressWarnings("unchecked")
	public void clearGames() {
		final PersistenceManager pm = PMF.getPM();

		try {
			final Query query = pm.newQuery(Game.class);
			final List<Game> games = (List<Game>) query.execute();

			pm.deletePersistentAll(games);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public void clearGame(String id) {
		final PersistenceManager pm = PMF.getPM();

		try {
			final Query query = pm.newQuery(Game.class);
			query.setFilter("key == keyParam");
			query.declareParameters(Key.class.getName() +" keyParam");

			final List<Game> games = (List<Game>) query.execute(Game.getKey(id));

			pm.deletePersistentAll(games);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public boolean gameExists(String id) {
		final PersistenceManager pm = PMF.getPM();

		try {
			final Query query = pm.newQuery(Game.class);
			query.setFilter("key == keyParam");
			query.declareParameters(Key.class.getName() +" keyParam");

			final List<Game> games = (List<Game>) query.execute(Game.getKey(id));

			return (!games.isEmpty());
		} finally {
			pm.close();
		}
	}

	public void storeGame(Game game) {
		final PersistenceManager pm = PMF.getPM();

		try {
			pm.makePersistent(game);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public Game loadGame(String id) {
		final PersistenceManager pm = PMF.getPM();

		try {
			final Query query = pm.newQuery(Game.class);
			query.setFilter("key == keyParam");
			query.declareParameters(Key.class.getName() +" keyParam");

			final List<Game> games = (List<Game>) query.execute(Game.getKey(id));

			if (games.isEmpty()) {
				throw new IllegalArgumentException("GameID is unknown");
			}
			if (games.size() > 1) {
				throw new IllegalArgumentException("GameID is ambigious");
			}

			return games.get(0);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Game> loadGames() {
		final PersistenceManager pm = PMF.getPM();

		try {
			final Query query = pm.newQuery(Game.class);
			final List<Game> games = (List<Game>) query.execute();

			return new ArrayList<Game>(games);
		} finally {
			pm.close();
		}
	}

	public List<Game> loadGamesWithPlayers() {
		final PlayerManager pm = new PlayerManager();
		final List<Game> games = loadGames();

		for (Game game : games) {
			final List<Key> keys = game.getPlayerKeys();
			for (Key key : keys) {
				if (!pm.playerExists(key.getName())) {
					System.err.println("Player "+ key +" does not exist!");
					continue;
				}

				final Player player = pm.loadPlayerById(key.getName());
				game.addPlayer(player);
			}
		}

		return games;
	}
}
